home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / hplip / base / g.py < prev    next >
Encoding:
Python Source  |  2009-04-14  |  10.6 KB  |  330 lines

  1. # -*- coding: utf-8 -*-
  2. #
  3. # (c) Copyright 2003-2009 Hewlett-Packard Development Company, L.P.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  18. #
  19. # Author: Don Welch
  20. #
  21. # NOTE: This module is safe for 'from g import *'
  22. #
  23.  
  24. # Std Lib
  25. import sys
  26. import os
  27. import os.path
  28. import ConfigParser
  29. import locale
  30. import pwd
  31. import stat
  32. import re
  33.  
  34. # Local
  35. from codes import *
  36. import logger
  37.  
  38. # System wide logger
  39. log = logger.Logger('', logger.Logger.LOG_LEVEL_INFO, logger.Logger.LOG_TO_CONSOLE)
  40. log.set_level('info')
  41.  
  42.  
  43. MINIMUM_PYQT_MAJOR_VER = 3
  44. MINIMUM_PYQT_MINOR_VER = 14
  45. MINIMUM_QT_MAJOR_VER = 3
  46. MINIMUM_QT_MINOR_VER = 0
  47.  
  48.  
  49. def to_bool(s, default=False):
  50.     if isinstance(s, str) and s:
  51.         if s[0].lower() in ['1', 't', 'y']:
  52.             return True
  53.         elif s[0].lower() in ['0', 'f', 'n']:
  54.             return False
  55.     elif isinstance(s, bool):
  56.         return s
  57.  
  58.     return default
  59.  
  60.  
  61. # System wide properties
  62. class Properties(dict):
  63.  
  64.     def __getattr__(self, attr):
  65.         if attr in self.keys():
  66.             return self.__getitem__(attr)
  67.         else:
  68.             return ""
  69.  
  70.     def __setattr__(self, attr, val):
  71.         self.__setitem__(attr, val)
  72.  
  73. prop = Properties()
  74.  
  75.  
  76.  
  77. class ConfigBase(object):
  78.     def __init__(self, filename):
  79.         self.filename = filename
  80.         self.conf = ConfigParser.ConfigParser()
  81.         self.read()
  82.  
  83.  
  84.     def get(self, section, key, default=u''):
  85.         try:
  86.             return self.conf.get(section, key)
  87.         except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
  88.             return default
  89.  
  90.  
  91.     def set(self, section, key, value):
  92.         if not self.conf.has_section(section):
  93.             self.conf.add_section(section)
  94.  
  95.         self.conf.set(section, key, value)
  96.         self.write()
  97.  
  98.  
  99.     def sections(self):
  100.         return self.conf.sections()
  101.  
  102.  
  103.     def has_section(self, section):
  104.         return self.conf.has_section(section)
  105.  
  106.  
  107.     def options(self, section):
  108.         return self.conf.options(section)
  109.  
  110.     keys = options
  111.  
  112.     def read(self):
  113.         if self.filename is not None:
  114.             try:
  115.                 fp = open(self.filename, "r")
  116.                 self.conf.readfp(fp)
  117.                 fp.close()
  118.             except (OSError, IOError):
  119.                 log.debug("Unable to open file %s for reading." % self.filename)
  120.  
  121.     def write(self):
  122.         if self.filename is not None:
  123.             try:
  124.                 fp = open(self.filename, "w")
  125.                 self.conf.write(fp)
  126.                 fp.close()
  127.             except (OSError, IOError):
  128.                 log.debug("Unable to open file %s for writing." % self.filename)
  129.  
  130.  
  131.  
  132. class SysConfig(ConfigBase):
  133.     def __init__(self):
  134.         ConfigBase.__init__(self, '/etc/hp/hplip.conf')
  135.  
  136.  
  137. class State(ConfigBase):
  138.     def __init__(self):
  139.         ConfigBase.__init__(self, '/var/lib/hp/hplip.state')
  140.  
  141.  
  142. class UserConfig(ConfigBase):
  143.     def __init__(self):
  144.         if not os.geteuid() == 0:
  145.             prop.user_dir = os.path.expanduser('~/.hplip')
  146.  
  147.             try:
  148.                 if not os.path.exists(prop.user_dir):
  149.                     os.makedirs(prop.user_dir)
  150.             except OSError:
  151.                 pass # This is sometimes OK, if running hpfax: for example
  152.  
  153.             prop.user_config_file = os.path.join(prop.user_dir, 'hplip.conf')
  154.  
  155.             if not os.path.exists(prop.user_config_file):
  156.                 try:
  157.                     file(prop.user_config_file, 'w').close()
  158.                     s = os.stat(os.path.dirname(prop.user_config_file))
  159.                     os.chown(prop.user_config_file, s[stat.ST_UID], s[stat.ST_GID])
  160.                 except IOError:
  161.                     pass
  162.  
  163.             ConfigBase.__init__(self, prop.user_config_file)
  164.  
  165.         else:
  166.             # If running as root, conf file is None
  167.             prop.user_dir = None
  168.             prop.user_config_file = None
  169.             ConfigBase.__init__(self, None)
  170.  
  171.  
  172.     def workingDirectory(self):
  173.         t = self.get('last_used', 'working_dir', os.path.expanduser("~"))
  174.         try:
  175.             t = t.decode('utf-8')
  176.         except UnicodeError:
  177.             log.error("Invalid unicode: %s"  % t)
  178.         log.debug("working directory: %s" % t)
  179.         return t
  180.  
  181.  
  182.     def setWorkingDirectory(self, t):
  183.         self.set('last_used', 'working_dir', t.encode('utf-8'))
  184.         log.debug("working directory: %s" % t.encode('utf-8'))
  185.  
  186.  
  187.  
  188. os.umask(0037)
  189.  
  190. # System Config File: Directories and build settings. Not altered after installation.
  191. sys_conf = SysConfig()
  192.  
  193. # System State File: System-wide runtime settings
  194. sys_state = State()
  195.  
  196. # Per-user Settings File:
  197. user_conf = UserConfig()
  198.  
  199.  
  200. # Language settings
  201. try:
  202.     prop.locale, prop.encoding = locale.getdefaultlocale()
  203. except ValueError:
  204.     prop.locale = 'en_US'
  205.     prop.encoding = 'UTF8'
  206.  
  207. prop.version = sys_conf.get('hplip', 'version', '0.0.0') # e.g., 3.9.2b.10
  208. _p, _x = re.compile(r'(\d*)', re.I), []
  209. for _y in prop.version.split('.')[:3]:
  210.     _z = _p.match(_y)
  211.     if _z is not None:
  212.         _x.append(_z.group(1))
  213.  
  214. prop.installed_version = '.'.join(_x) # e.g., '3.9.2'
  215. try:
  216.     prop.installed_version_int = int(''.join(['%02x' % int(_y) for _y in _x]), 16) # e.g., 0x030902 -> 198914
  217. except ValueError:
  218.     prop.installed_version_int = 0
  219.  
  220. prop.home_dir = sys_conf.get('dirs', 'home', os.path.realpath(os.path.normpath(os.getcwd())))
  221. prop.username = pwd.getpwuid(os.getuid())[0]
  222. pdb = pwd.getpwnam(prop.username)
  223. prop.userhome = pdb[5]
  224.  
  225. prop.history_size = 50
  226.  
  227. prop.data_dir = os.path.join(prop.home_dir, 'data')
  228. prop.image_dir = os.path.join(prop.home_dir, 'data', 'images')
  229. prop.xml_dir = os.path.join(prop.home_dir, 'data', 'xml')
  230. prop.models_dir = os.path.join(prop.home_dir, 'data', 'models')
  231. prop.localization_dir = os.path.join(prop.home_dir, 'data', 'localization')
  232.  
  233. prop.max_message_len = 8192
  234. prop.max_message_read = 65536
  235. prop.read_timeout = 90
  236.  
  237. prop.ppd_search_path = '/usr/share;/usr/local/share;/usr/lib;/usr/local/lib;/usr/libexec;/opt;/usr/lib64'
  238. prop.ppd_search_pattern = 'HP-*.ppd.*'
  239. prop.ppd_download_url = 'http://www.linuxprinting.org/ppd-o-matic.cgi'
  240. prop.ppd_file_suffix = '-hpijs.ppd'
  241.  
  242. # Build and install configurations
  243. prop.gui_build = to_bool(sys_conf.get('configure', 'gui-build', '0'))
  244. prop.net_build = to_bool(sys_conf.get('configure', 'network-build', '0'))
  245. prop.par_build = to_bool(sys_conf.get('configure', 'pp-build', '0'))
  246. prop.usb_build = True
  247. prop.scan_build = to_bool(sys_conf.get('configure', 'scanner-build', '0'))
  248. prop.fax_build = to_bool(sys_conf.get('configure', 'fax-build', '0'))
  249. prop.doc_build = to_bool(sys_conf.get('configure', 'doc-build', '0'))
  250. prop.foomatic_xml_install = to_bool(sys_conf.get('configure', 'foomatic-xml-install', '0'))
  251. prop.foomatic_ppd_install = to_bool(sys_conf.get('configure', 'foomatic-ppd-install', '0'))
  252.  
  253. # Spinner, ala Gentoo Portage
  254. spinner = "\|/-\|/-"
  255. spinpos = 0
  256.  
  257. def update_spinner():
  258.     global spinner, spinpos
  259.     if not log.is_debug() and sys.stdout.isatty():
  260.         sys.stdout.write("\b" + spinner[spinpos])
  261.         spinpos=(spinpos + 1) % 8
  262.         sys.stdout.flush()
  263.  
  264. def cleanup_spinner():
  265.     if not log.is_debug() and sys.stdout.isatty():
  266.         sys.stdout.write("\b \b")
  267.         sys.stdout.flush()
  268.  
  269.  
  270. # Internal/messaging errors
  271.  
  272. ERROR_STRINGS = {
  273.                 ERROR_SUCCESS : 'No error',
  274.                 ERROR_UNKNOWN_ERROR : 'Unknown error',
  275.                 ERROR_DEVICE_NOT_FOUND : 'Device not found',
  276.                 ERROR_INVALID_DEVICE_ID : 'Unknown/invalid device-id field',
  277.                 ERROR_INVALID_DEVICE_URI : 'Unknown/invalid device-uri field',
  278.                 ERROR_DATA_LENGTH_EXCEEDS_MAX : 'Data length exceeds maximum',
  279.                 ERROR_DEVICE_IO_ERROR : 'Device I/O error',
  280.                 ERROR_NO_PROBED_DEVICES_FOUND : 'No probed devices found',
  281.                 ERROR_DEVICE_BUSY : 'Device busy',
  282.                 ERROR_DEVICE_STATUS_NOT_AVAILABLE : 'DeviceStatus not available',
  283.                 ERROR_INVALID_SERVICE_NAME : 'Invalid service name',
  284.                 ERROR_ERROR_INVALID_CHANNEL_ID : 'Invalid channel-id (service name)',
  285.                 ERROR_CHANNEL_BUSY : 'Channel busy',
  286.                 ERROR_DEVICE_DOES_NOT_SUPPORT_OPERATION : 'Device does not support operation',
  287.                 ERROR_DEVICEOPEN_FAILED : 'Device open failed',
  288.                 ERROR_INVALID_DEVNODE : 'Invalid device node',
  289.                 ERROR_INVALID_HOSTNAME : "Invalid hostname ip address",
  290.                 ERROR_INVALID_PORT_NUMBER : "Invalid JetDirect port number",
  291.                 ERROR_NO_CUPS_QUEUE_FOUND_FOR_DEVICE : "No CUPS queue found for device.",
  292.                 ERROR_DATFILE_ERROR: "DAT file error",
  293.                 ERROR_INVALID_TIMEOUT: "Invalid timeout",
  294.                 ERROR_IO_TIMEOUT: "I/O timeout",
  295.                 ERROR_FAX_INCOMPATIBLE_OPTIONS: "Incompatible fax options",
  296.                 ERROR_FAX_INVALID_FAX_FILE: "Invalid fax file",
  297.                 ERROR_FAX_FILE_NOT_FOUND: "Fax file not found",
  298.                 ERROR_INTERNAL : 'Unknown internal error',
  299.                }
  300.  
  301.  
  302. class Error(Exception):
  303.     def __init__(self, opt=ERROR_INTERNAL):
  304.         self.opt = opt
  305.         self.msg = ERROR_STRINGS.get(opt, ERROR_STRINGS[ERROR_INTERNAL])
  306.         log.debug("Exception: %d (%s)" % (opt, self.msg))
  307.         Exception.__init__(self, self.msg, opt)
  308.  
  309.  
  310. # Make sure True and False are avail. in pre-2.2 versions
  311. try:
  312.     True
  313. except NameError:
  314.     True = (1==1)
  315.     False = not True
  316.  
  317. # as new translations are completed, add them here
  318. supported_locales =  { 'en_US': ('us', 'en', 'en_us', 'american', 'america', 'usa', 'english'),}
  319. # Localization support was disabled in 3.9.2
  320.                        #'zh_CN': ('zh', 'cn', 'zh_cn' , 'china', 'chinese', 'prc'),
  321.                        #'de_DE': ('de', 'de_de', 'german', 'deutsche'),
  322.                        #'fr_FR': ('fr', 'fr_fr', 'france', 'french', 'fran√ßais'),
  323.                        #'it_IT': ('it', 'it_it', 'italy', 'italian', 'italiano'),
  324.                        #'ru_RU': ('ru', 'ru_ru', 'russian'),
  325.                        #'pt_BR': ('pt', 'br', 'pt_br', 'brazil', 'brazilian', 'portuguese', 'brasil', 'portuguesa'),
  326.                        #'es_MX': ('es', 'mx', 'es_mx', 'mexico', 'spain', 'spanish', 'espanol', 'espa√±ol'),
  327.                      #}
  328.  
  329.  
  330.